<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script>
			/*
			 * 工厂方法创建对象
			 */
			function person(name, age){
				// 创建一个新对象
				var obj = new Object();
				// 向对象中添加属性
				obj.name = name;
				obj.age = age;
				obj.test = function(){
					console.log("person");
				}
				// 将新的对象返回
				return obj;
			}
			
			var per = person("孙悟空", 18);
			per.test();
			console.log(per);
			console.log("\n");
			
			/*
			 * 构造方法创建对象
			 * 流程:
			 * 		1.立刻创建一个新的对象
			 * 		2.将新建的对象设置为函数中的this, 在构造函数中可以使用this来引用新的对象
			 * 		3.逐行执行函数中的代码
			 * 		4.将新建的对象作为返回值返回
			 */
			function Person(name, age){
				this.name = name;
				this.age = age;
				this.test = function(){
					console.log("Person");
				}
			}
			
			var per2 = new Person("孙悟空", 18);
			per2.test();
			console.log(per2);
			
			console.log(per instanceof Object);  //true
			console.log(per2 instanceof Person); //true
			console.log(per2 instanceof Object); //true
			console.log("\n");
			
			//增强版
			function Pers(name, age){
				this.name = name;
				this.age = age;
				this.test = fun;
			}
			
			function fun(){
				console.log(this.name);
			}
			
			var per3 = new Pers("孙悟空", 18);
			per3.test();
			console.log(per3);
			var per4 = new Pers("猪八戒", 28);
			per4.test();
			console.log(per4);
			console.log(per3.test == per4.test);
			console.log("\n");
			
			//使用原型
			function Per(name, age){
				this.name = name;
				this.age = age;
			}
			
			Per.prototype.test = function(){
				console.log(this.name);
			}
			var sun = new Per("孙悟空", 18);
			sun.test();
			
			// 修改Per原型的toString()
			Per.prototype.toString = function(){
				return "Per [name="+ this.name +", age="+this.age+"]";
			}
			console.log(sun.toString());
		</script>
	</head>
	<body>
	</body>
</html>
